using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.XML;

namespace ThisGrayWorldAI
{
    
    public sealed static class ClientServerInterface
    {
        private sealed static class RuntimeProperties
        {
            public static AppDomain     ServerDomain;
            public static int           ServerDomainHashCode; // Just in case amirite
            public static Guid          SessionGuid;
            public static string        ServerDomainName;
            public static string        CrossDomainSingletonName;

            public static string        ConfigFilename = "AIInterfaceConfig.xml";
            public static XmlDocument   ConfigFile;
            public static string        ConfigAppDomainNamePath = "/ThisGrayWorldAI/ServerAppDomainName"; // Maybe make it a proper XPath some day aah no fukkit
            public static string        ConfigCrossDomainSingletonNamePath = "/ThisGrayWorldAI/CrossDomainSingletonName";
        }

        private static ClientServerInterface()
        {
            RuntimeProperties.SessionGuid = Guid.NewGuid();
            ReadXmlConfig();
        }

        public static void LaunchServer()
        {
            var Server = AppDomain.CreateDomain(RuntimeProperties.ServerDomainName);
            Server.SetData(RuntimeProperties.CrossDomainSingletonName, CrossDomainSingleton.Instance);

            RuntimeProperties.ServerDomain = Server;
            RuntimeProperties.ServerDomainHashCode = Server.GetHashCode();
        } 

        private static string ExtractXmlNode(string NodeXPath)
        {
             XmlNode DesiredNode = ConfigFile.SelectNodes(NodeXPath)[0];
             return DesiredNode.InnerText();            
        }

        private static void ReadXmlConfig()
        {
            try 
            {
                ConfigFile = new XmlDocument();
                ConfigFile.Load(RuntimeProperties.ConfigFilename);

                RuntimeProperties.ServerDomainName = ExtractXmlNode(RuntimeProperties.ConfigAppDomainNamePath);
                RuntimeProperties.CrossDomainSingletonName = ExtractXmlNode(RuntimeProperties.ConfigCrossDomainSingletonNamePath);

            } 
            catch (System.Exception e) 
            {
                throw; // Let those suckers from top handle this
            }
        }
    }

    public sealed class CrossDomainSingleton : MarshalByRefObject
    {
        private static CrossDomainSingleton instance = null;

        public static CrossDomainSingleton Instance
        {
            get {
                return instance ?? (instance = AppDomain.CurrentDomain.GetData(RuntimeProperties.CrossDomainSingletonName) as Singleton);
            }
        }
    }

    public interface ICharacterEntityTemplate 
    {
        string      InitialName, CurrentName;
        


    }
}
